/* File Name : EventDelegate.java */
//Jose Heitor

package com.chenwenxuan.sync.event;

import java.util.Hashtable;

// One instance of this class is created by the EventsManager class for each event type that a 
// source object generates. (The EventsManager class manages the list of events that the source generates.)
// This class manages the list of listeners that wish to be notified of this type of event.
class EventDelegate
{
  private final EventDispatcher eventDispatcher;
  private final Object source;
  private final Hashtable<Object, EventObserver> handlers;
  private final String eventType;
  private final int threadPriority;
  private final boolean queue;
  private Thread thDisp = null;
  
  // Optional constructor. Requires a reference to the event source object and the name of the event that
  // this class is managing.
  public EventDelegate(IEventSource source, String eventType)
  {
    this(source, eventType, 0, false);
  }
  
  // Optional constructor. Requires a reference to the event source object and the name of the event that
  // this class is managing. The optional threadPriority parameter sets the threading model for this event.
  public EventDelegate(IEventSource source, String eventType, int threadPriority)
  {
    this(source, eventType, threadPriority, false);
  }
  
  // Optional constructor. Requires a reference to the event source object and the name of the event that
  // this class is managing. The optional threadPriority parameter sets the threading model for this event.
  // The optional queue parameter determines the use of an events message queue.
  public EventDelegate(IEventSource source, String eventType, int threadPriority, boolean queue)
  {
    this.source = source;
    this.eventType = eventType;
    this.threadPriority = threadPriority;
    this.queue = queue;
    eventDispatcher = new EventDispatcher(source, threadPriority, queue);
    handlers = new Hashtable<Object, EventObserver>();
    if (threadPriority > 0)
    {
      thDisp = new Thread(eventDispatcher, eventType);
      thDisp.start();
    }
  }
  
  // Forwards the event parameters for the event that was fired to the EventDispatcher that will
  // notify all the registered listeners.
  void raiseEvent(Object params)
  {
    eventDispatcher.dispatchEvent(params);
  }
  
  // Registers a new Observer (listener-proxy) object with the EventDispatcher for this event.
  void addEventHandler(EventObserver observer)
  {
    handlers.put(observer.getTarget(), observer);
    eventDispatcher.addObserver(observer);
  }
  
  // De-registers a listener object from receiving notifications from the EventDispatcher for this event.
  void removeEventHandler(Object target)
  {
    eventDispatcher.deleteObserver(handlers.get(target));
    eventDispatcher.deActivate();
    handlers.remove(target);
  }
}

